import parole, pygame

import random, pickle
from datetime import datetime
import main
from util import *

class HighScore(object):

    def __init__(self):
        self.entries = []

    def addEntry(self, entry):
        self.entries.append(entry)
        self.entries.sort()

    def save(self):
        try:
            f = open('highscore.pkl', 'w')
            pickle.dump(self, f)
            f.close()
            parole.info('Highscore saved.')
        except:
            parole.error('Unable to save highscore!')

    def __len__(self):
        return len(self.entries)

    def __str__(self):
        return '\n\n'.join([str(e) for e in self.entries])

def getHighScore():
    try:
        f = open('highscore.pkl', 'r')
        highScore = pickle.load(f)
        f.close()
        parole.info('Highscore read from %s.', f.name)
        return highScore
    except:
        parole.info('Unable to read highscore from highscore.pkl. Starting new'
                ' one.')
        return HighScore()

class Entry(object):

    def __init__(self, player, where):
        self.playerName = player.playerName
        self.xp = player.xp
        self.level = player.level
        self.won = player.winner
        self.dead = player.dead
        if player.lastDamageSource:
            self.lastDamageSource = str(player.lastDamageSource)
        else:
            self.lastDamageSource = 'nothing'
        self.gameTime = main.schedule.time
        self.when = datetime.now()
        self.where = where

    def __cmp__(self, otherEntry):
        return -cmp(self.xp, otherEntry.xp)
        
    def __str__(self):
        if self.won:
            status = 'Won'
        elif self.dead:
            status = 'Killed by %s' % self.lastDamageSource
        else:
            status = 'Still alive'
        status += (' in %s' % self.where)

        return '%s: %d XP, level %d (%s).\n\t%s\n\tafter %s.' % \
            (self.playerName, self.xp, self.level, self.when.ctime(),
                    status, durationStr(self.gameTime))


